package com.gitee.wsl.doc.prosemirror.state.command

import com.gitee.wsl.doc.prosemirror.model.node.NodeType
import com.gitee.wsl.doc.prosemirror.state.Command
import com.gitee.wsl.doc.prosemirror.state.CommandDispatch
import com.gitee.wsl.doc.prosemirror.state.EditorState

class InsertProperty(
    val propertyType: NodeType,
    val name: String,
    val placeholder: String
    ): Command {
    override fun exec(
        state: EditorState,
        dispatch: CommandDispatch?,
    ): Boolean {
        val from = state.selection._from
        val index = from.index()

        if (!from.parent.canReplaceWith(index, index, propertyType)) {
            return false
        }

       dispatch?.apply(state.tr.replaceSelectionWith(propertyType.create(attrs = mapOf( "name" to name, "placeholder" to placeholder))))
       return true
    }
}

fun Command.Companion.insertProperty(
    propertyType: NodeType,
    name: String,
    placeholder: String ) = InsertProperty(propertyType,name,placeholder)